package com.famiover.generator;

import com.google.common.collect.Lists;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.InitializationBlock;

import java.util.List;
import java.util.ListIterator;

public class Constructor extends InitializationBlock {

    private List<String> bodyLines = Lists.newArrayList();

    @Override
    public List<String> getBodyLines() {
        return bodyLines;
    }

    public void addBodyLine(String bodyLine) {
        bodyLines.add(bodyLine);
    }

    public void setBodyLines(List<String> bodyLines) {
        this.bodyLines = bodyLines;
    }

    public String getFormattedContent(int indentLevel) {
        StringBuilder sb = new StringBuilder();
        indentLevel = 1;
        OutputUtilities.javaIndent(sb, indentLevel);
        indentLevel++;
        ListIterator<String> listIter = bodyLines.listIterator();
        while (listIter.hasNext()) {
            String line = listIter.next();
            if (line.startsWith("}")) {
                indentLevel--;
            }
            OutputUtilities.newLine(sb);
            OutputUtilities.javaIndent(sb, indentLevel);
            sb.append(line);
            if ((line.endsWith("{") && !line.startsWith("switch")) || line.endsWith(":")) {
                indentLevel++;
            }
            if (line.startsWith("break")) {
                if (listIter.hasNext()) {
                    String nextLine = listIter.next();
                    if (nextLine.startsWith("}")) {
                        indentLevel++;
                    }
                    listIter.previous();
                }
                indentLevel--;
            }
        }
        indentLevel--;
        OutputUtilities.newLine(sb);
        OutputUtilities.javaIndent(sb, indentLevel);
        return sb.toString();
    }
}
